<template>
  <div class="system-container">
    <!-- 系统基本信息 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="system-card">
          <div slot="header" class="card-header">
            <span class="card-title">
              <i class="el-icon-monitor"></i>
              系统信息
            </span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">系统名称</span>
                <el-tag type="info">
                  <i class="el-icon-apple"></i>
                  {{ system.name }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">系统版本</span>
                <el-tag type="success">
                  <i class="el-icon-version"></i>
                  {{ system.release }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">主机名</span>
                <el-tag type="warning">
                  <i class="el-icon-monitor"></i>
                  {{ system.hostname }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">系统架构</span>
                <el-tag type="danger">
                  <i class="el-icon-cpu"></i>
                  {{ system.architecture }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">CPU型号</span>
                <el-tag type="info">
                  <i class="el-icon-cpu"></i>
                  {{ extras.cpu_brand }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">macOS版本</span>
                <el-tag type="success">
                  <i class="el-icon-apple"></i>
                  {{ extras.macos_version }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
          <div class="system-version">
            <el-tag type="info" effect="plain" size="small">
              <i class="el-icon-info"></i>
              {{ system.version }}
            </el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- CPU和内存信息 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card class="cpu-card">
          <div slot="header" class="card-header">
            <span class="card-title">
              <i class="el-icon-cpu"></i>
              CPU 使用率
            </span>
          </div>
          <div class="cpu-info">
            <div class="total-cpu">
              <el-progress type="dashboard" :percentage="cpu.total_percent" :color="getCpuColor">
                <template slot="default">
                  <div class="progress-label">
                    <span class="percentage">{{ cpu.total_percent }}%</span>
                    <span class="label">总使用率</span>
                  </div>
                </template>
              </el-progress>
            </div>
            <div class="cpu-cores">
              <div v-for="(core, index) in cpu.per_core_percent" :key="index" class="core-item">
                <span class="core-label">
                  <i class="el-icon-connection"></i>
                  核心 {{ index + 1 }}
                </span>
                <el-progress :percentage="core" :color="getCpuColor"></el-progress>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="memory-card">
          <div slot="header" class="card-header">
            <span class="card-title">
              <i class="el-icon-coin"></i>
              内存使用情况
            </span>
          </div>
          <div class="memory-info">
            <el-progress type="dashboard" :percentage="memory.percent" :color="getMemoryColor">
              <template slot="default">
                <div class="progress-label">
                  <span class="percentage">{{ memory.percent }}%</span>
                  <span class="label">内存使用率</span>
                </div>
              </template>
            </el-progress>
            <div class="memory-details">
              <div class="detail-item">
                <span class="label">
                  <i class="el-icon-data-analysis"></i>
                  总内存
                </span>
                <span class="value">{{ formatBytes(memory.total) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">
                  <i class="el-icon-data-line"></i>
                  已使用
                </span>
                <span class="value">{{ formatBytes(memory.used) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">
                  <i class="el-icon-data-board"></i>
                  可用
                </span>
                <span class="value">{{ formatBytes(memory.available) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 磁盘信息 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="disk-card">
          <div slot="header" class="card-header">
            <span class="card-title">
              <i class="el-icon-folder"></i>
              磁盘使用情况
            </span>
          </div>
          <div class="disk-list">
            <div v-for="(usage, mountpoint) in disk.usage" :key="mountpoint" class="disk-item">
              <div class="disk-header">
                <span class="mountpoint">
                  <i class="el-icon-folder-opened"></i>
                  {{ mountpoint }}
                </span>
                <span class="usage-percent">
                  <el-tag :type="getDiskColorType(usage.percent)" size="small">
                    {{ usage.percent }}%
                  </el-tag>
                </span>
              </div>
              <el-progress :percentage="usage.percent" :color="getDiskColor(usage.percent)"></el-progress>
              <div class="disk-details">
                <span>
                  <i class="el-icon-data-analysis"></i>
                  总空间: {{ formatBytes(usage.total) }}
                </span>
                <span>
                  <i class="el-icon-data-line"></i>
                  已用: {{ formatBytes(usage.used) }}
                </span>
                <span>
                  <i class="el-icon-data-board"></i>
                  可用: {{ formatBytes(usage.free) }}
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 网络信息 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="network-card">
          <div slot="header" class="card-header">
            <span class="card-title">
              <i class="el-icon-connection"></i>
              网络接口
            </span>
          </div>
          <el-table :data="networkInterfaces" style="width: 100%">
            <el-table-column prop="name" label="接口名称" width="120">
              <template slot-scope="scope">
                <span>
                  <i class="el-icon-connection"></i>
                  {{ scope.row.name }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="IP地址" width="180">
              <template slot-scope="scope">
                <el-tag size="small" type="info">{{ scope.row.address }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="netmask" label="子网掩码" width="180">
              <template slot-scope="scope">
                <el-tag size="small" type="warning">{{ scope.row.netmask }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isup ? 'success' : 'danger'" size="small">
                  <i :class="scope.row.isup ? 'el-icon-success' : 'el-icon-error'"></i>
                  {{ scope.row.isup ? '在线' : '离线' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="mtu" label="MTU" width="100">
              <template slot-scope="scope">
                <el-tag size="small" type="info">{{ scope.row.mtu }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="flags" label="标志">
              <template slot-scope="scope">
                <el-tag size="small" type="info" effect="plain">{{ scope.row.flags }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 防火墙信息 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="firewall-card">
          <div slot="header" class="card-header">
            <span class="card-title">
              <i class="el-icon-lock"></i>
              防火墙配置
            </span>
            <el-button 
              v-if="firewallConfig.firewall === 'UFW'"
              type="primary" 
              size="small" 
              @click="showAddPortDialog">
              <i class="el-icon-plus"></i>
              添加端口
            </el-button>
          </div>
          <el-tabs type="border-card">
            <el-tab-pane label="防火墙状态">
              <div class="firewall-status">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <div class="status-item">
                      <span class="label">防火墙类型：</span>
                      <el-tag type="info" size="medium">
                        {{ firewallConfig.firewall }}
                      </el-tag>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="status-item">
                      <span class="label">防火墙状态：</span>
                      <el-tag :type="firewallConfig.is_active ? 'success' : 'danger'" size="medium">
                        <i :class="firewallConfig.is_active ? 'el-icon-success' : 'el-icon-error'"></i>
                        {{ firewallConfig.is_active ? '已启用' : '已禁用' }}
                      </el-tag>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>
            <el-tab-pane label="防火墙规则" v-if="firewallConfig.firewall === 'UFW'">
              <div class="firewall-rules">
                <el-table :data="firewallConfig.rules" style="width: 100%">
                  <el-table-column prop="port" label="端口" width="120">
                    <template slot-scope="scope">
                      <el-tag size="small" type="info">{{ scope.row.port }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="protocol" label="协议" width="120">
                    <template slot-scope="scope">
                      <el-tag size="small" type="warning">{{ scope.row.protocol }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="action" label="动作" width="120">
                    <template slot-scope="scope">
                      <el-tag size="small" :type="scope.row.action === 'ALLOW' ? 'success' : 'danger'">
                        {{ scope.row.action }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="description" label="描述"></el-table-column>
                  <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="danger"
                        @click="handleDeletePort(scope.row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加端口对话框 -->
    <el-dialog
      title="添加端口"
      :visible.sync="addPortDialogVisible"
      width="30%">
      <el-form :model="newPort" :rules="portRules" ref="portForm" label-width="80px">
        <el-form-item label="端口" prop="port">
          <el-input-number v-model="newPort.port" :min="1" :max="65535"></el-input-number>
        </el-form-item>
        <el-form-item label="协议" prop="protocol">
          <el-select v-model="newPort.protocol" placeholder="请选择协议">
            <el-option label="TCP" value="tcp"></el-option>
            <el-option label="UDP" value="udp"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="newPort.description" placeholder="请输入端口描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPortDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddPort">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchSystemInfo, fetchFirewallConfig, addUfwPort, deleteUfwPort } from '@/api/opration'
import { Descriptions, DescriptionsItem } from 'element-ui'

export default {
  name: 'Config',
  components: {
    'el-descriptions': Descriptions,
    'el-descriptions-item': DescriptionsItem
  },
  data() {
    return {
      system: {},
      cpu: {},
      memory: {},
      disk: {},
      network: {},
      sensors: {},
      uptime: {},
      extras: {},
      firewallConfig: {
        firewall: '',
        is_active: false,
        rules: []
      },
      addPortDialogVisible: false,
      newPort: {
        port: 80,
        protocol: 'tcp',
        description: ''
      },
      portRules: {
        port: [
          { required: true, message: '请输入端口号', trigger: 'blur' }
        ],
        protocol: [
          { required: true, message: '请选择协议', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    networkInterfaces() {
      const interfaces = []
      for (const [name, stats] of Object.entries(this.network.stats || {})) {
        const addresses = this.network.interfaces[name] || []
        const ipv4 = addresses.find(addr => addr.family === 2)
        interfaces.push({
          name,
          address: ipv4 ? ipv4.address : '-',
          netmask: ipv4 ? ipv4.netmask : '-',
          isup: stats.isup,
          mtu: stats.mtu,
          flags: stats.flags
        })
      }
      return interfaces
    },
    getCpuColor() {
      return (percentage) => {
        if (percentage < 60) return '#67C23A'
        if (percentage < 80) return '#E6A23C'
        return '#F56C6C'
      }
    },
    getMemoryColor() {
      return (percentage) => {
        if (percentage < 60) return '#67C23A'
        if (percentage < 80) return '#E6A23C'
        return '#F56C6C'
      }
    }
  },
  methods: {
    formatBytes(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    getDiskColor(percent) {
      if (percent < 60) return '#67C23A'
      if (percent < 80) return '#E6A23C'
      return '#F56C6C'
    },
    getDiskColorType(percent) {
      if (percent < 60) return 'success'
      if (percent < 80) return 'warning'
      return 'danger'
    },
    showAddPortDialog() {
      this.addPortDialogVisible = true
      this.newPort = {
        port: 80,
        protocol: 'tcp',
        description: ''
      }
    },
    async handleAddPort() {
      try {
        await this.$refs.portForm.validate()
        await addUfwPort(this.newPort)
        this.addPortDialogVisible = false
        this.$message.success('端口添加成功')
        this.fetchFirewallConfig()
      } catch (error) {
        console.error('添加端口失败:', error)
        this.$message.error('添加端口失败')
      }
    },
    async handleDeletePort(rule) {
      try {
        await this.$confirm('确认删除该端口规则吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteUfwPort({
          port: rule.port,
          protocol: rule.protocol
        })
        this.$message.success('端口删除成功')
        this.fetchFirewallConfig()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除端口失败:', error)
          this.$message.error('删除端口失败')
        }
      }
    },
    async fetchSystemInfo() {
      try {
        const response = await fetchSystemInfo()
        if (response) {
          this.system = response.system || {}
          this.cpu = response.cpu || {}
          this.memory = response.memory || {}
          this.disk = response.disk || {}
          this.network = response.network || {}
          this.sensors = response.sensors || {}
          this.uptime = response.uptime || {}
          this.extras = response.extras || {}
        } else {
          this.$message.error('获取系统信息失败')
        }
      } catch (error) {
        console.error('获取系统信息失败:', error)
        this.$message.error('获取系统信息失败')
      }
    },
    async fetchFirewallConfig() {
      try {
        const response = await fetchFirewallConfig()
        if (response) {
          this.firewallConfig = response
        } else {
          this.$message.error('获取防火墙配置失败')
        }
      } catch (error) {
        console.error('获取防火墙配置失败:', error)
        this.$message.error('获取防火墙配置失败')
      }
    }
  },
  mounted() {
    this.fetchSystemInfo()
    this.fetchFirewallConfig()
    // 每5秒更新一次数据
    this.timer = setInterval(() => {
      this.fetchSystemInfo()
      this.fetchFirewallConfig()
    }, 5000)
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style lang="scss" scoped>
.system-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .el-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
    }

    .card-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
  }

  .cpu-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;

    .total-cpu {
      margin-bottom: 30px;
    }

    .cpu-cores {
      width: 100%;
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 15px;

      .core-item {
        .core-label {
          display: flex;
          align-items: center;
          i {
            margin-right: 5px;
            color: #409EFF;
          }
        }
      }
    }
  }

  .memory-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;

    .memory-details {
      margin-top: 30px;
      width: 100%;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;

      .detail-item {
        text-align: center;

        .label {
          display: flex;
          align-items: center;
          i {
            margin-right: 5px;
            color: #409EFF;
          }
        }

        .value {
          font-size: 16px;
          color: #303133;
          font-weight: bold;
        }
      }
    }
  }

  .disk-list {
    .disk-item {
      margin-bottom: 20px;
      padding: 15px;
      background-color: #f8f9fb;
      border-radius: 4px;

      &:last-child {
        margin-bottom: 0;
      }

      .disk-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;

        .mountpoint {
          display: flex;
          align-items: center;
          i {
            margin-right: 5px;
            color: #409EFF;
          }
        }

        .usage-percent {
          color: #909399;
        }
      }

      .disk-details {
        margin-top: 10px;
        display: flex;
        justify-content: space-between;
        color: #606266;
        font-size: 13px;

        span {
          display: flex;
          align-items: center;
          i {
            margin-right: 5px;
            color: #409EFF;
          }
        }
      }
    }
  }

  .progress-label {
    text-align: center;

    .percentage {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
    }

    .label {
      display: block;
      color: #909399;
      margin-top: 5px;
    }
  }

  .system-card {
    .card-header {
      display: flex;
      align-items: center;
      .card-title {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
        display: flex;
        align-items: center;
        i {
          margin-right: 8px;
          font-size: 18px;
          color: #409EFF;
        }
      }
    }

    .el-descriptions {
      margin: 20px 0;
      ::v-deep .el-descriptions-item__label {
        width: 120px;
        font-weight: bold;
        color: #606266;
      }
      ::v-deep .el-descriptions-item__content {
        .el-tag {
          min-width: 120px;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
          i {
            margin-right: 5px;
            font-size: 14px;
          }
        }
      }
    }

    .system-version {
      margin-top: 20px;
      text-align: center;
      .el-tag {
        max-width: 100%;
        white-space: normal;
        height: auto;
        line-height: 1.5;
        padding: 8px 12px;
        display: inline-flex;
        align-items: center;
        i {
          margin-right: 5px;
          font-size: 14px;
        }
      }
    }
  }

  .el-table {
    ::v-deep .el-table__row {
      td {
        .el-tag {
          display: inline-flex;
          align-items: center;
          i {
            margin-right: 5px;
          }
        }
      }
    }
  }

  .firewall-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .firewall-status {
      padding: 20px;
      .status-item {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        .label {
          font-size: 14px;
          color: #606266;
          margin-right: 10px;
          min-width: 120px;
        }
        .el-tag {
          font-size: 14px;
          padding: 8px 15px;
          i {
            margin-right: 5px;
          }
        }
      }
    }

    .firewall-rules {
      padding: 20px;
      .el-table {
        margin-top: 10px;
      }
    }
  }

  .info-item {
    margin-bottom: 20px;
    .label {
      display: block;
      font-size: 14px;
      color: #606266;
      margin-bottom: 8px;
      font-weight: bold;
    }
    .el-tag {
      min-width: 120px;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      i {
        margin-right: 5px;
        font-size: 14px;
      }
    }
  }
}
</style>
